//
//  HMEmoticonKeyboardView.swift
//  EmoticonKeyboard
//
//  Created by 周英培 on 16/5/30.
//  Copyright © 2016年 周英培. All rights reserved.
//
/*
 1.6plus 6splus 键盘是226  其他的都是216
 2.StackView 是一个容器视图 不负责视图的渲染 是用来装取视图的 它自己本身 是不会渲染的
 */
import UIKit
import SnapKit
private let emoticonKeyboardViewHeight : CGFloat = 226
private let toolbarHeight : CGFloat = 37
private let emoticonCellID = "emoticonCellID"
class HMEmoticonKeyboardView: UIView {
    
    //组模型数组
    lazy var packages : [HMEmoticonPackage] = HMEmoticonManager.sharedEmoticonTools.packages

    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: 0, width: 0, height: 226)
        
        super.init(frame: rect)
//        self.backgroundColor = UIColor.redColor()
        setUpUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:设置UI界面
    private func setUpUI() {
        addSubview(toolbar)
        addSubview(EmoticonView)
        addSubview(pageControl)
        
        //设置约束
        toolbar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
            // 设置高度
            make.height.equalTo(toolbarHeight)
        }
        
        EmoticonView.snp_makeConstraints { (make) in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(toolbar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.bottom.equalTo(toolbar.snp_top).offset(-5)
        }
        //实现闭包
        toolbar.selectedIndexBtnClick = {(index : Int) in
        
            print(index)
            
            //跟toolbal的三个按钮相联系
            let indexPath = NSIndexPath(forItem: 0, inSection: index)
            
            self.EmoticonView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            
            //实现这一句 就能能够实现 点击表情下面toolbar时 能对应到应该的页书
            self.updatePagecontroll(indexPath)
        
        }
        
        //不能写在这里会崩溃
        //设置初始化的时候默认的pagecontroll
//        let indexPath = NSIndexPath(forItem: 0, inSection: 0)
//        updatePagecontroll(indexPath)
        
        dispatch_async(dispatch_get_main_queue()) { 
            //设置初始化的时候默认的pagecontroll
            let indexPath = NSIndexPath(forItem: 0, inSection: 0)
            self.updatePagecontroll(indexPath)
        }
    
    }
    
//    override func layoutSubviews() {
//        //设置初始化的时候默认的pagecontroll
//        let indexPath = NSIndexPath(forItem: 0, inSection: 0)
//        updatePagecontroll(indexPath)
//    }
    
    //MARK:懒加载子控件
    //tllobar
    private lazy var toolbar : HMEmoticonToolBar = HMEmoticonToolBar()
    
    //pageControl控件 即分页指示器
    private lazy var pageControl : UIPageControl = {
    
        let p = UIPageControl()
        
        //设置页数
        p.numberOfPages = 6
        
        //设置当前页数
        p.currentPage = 3
        
        //设置不交互状态
        p.userInteractionEnabled = false
        
        //系统的
//        p.pageIndicatorTintColor = UIColor.blueColor()
//        p.currentPageIndicatorTintColor = UIColor.orangeColor()
        
        //通过KVC自定义设置分页指示器的小图标
        p.setValue(UIImage(named:"compose_keyboard_dot_normal"), forKey: "_pageImage")
        p.setValue(UIImage(named:"compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return p
    
    }()
    
    //表情视图
    private lazy var  EmoticonView : UICollectionView = {
    
        //设置流水布局
        let layout = UICollectionViewFlowLayout()
        
        //设置itemsize
        layout.itemSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: emoticonKeyboardViewHeight - toolbarHeight)
        
        //设置滚动方向
        layout.scrollDirection = .Horizontal
        
        //设置行 列 间距
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        //设置数据源代理
        cv.dataSource = self
        
        //设置代理
        cv.delegate = self
        
        //关闭弹簧效果
        cv.bounces = false
        
        //设置分页滚动
        cv.pagingEnabled = true
        
        //设置颜色
        cv.backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        //注册cell
        cv.registerClass(HMEmoticonPageCell.self, forCellWithReuseIdentifier: emoticonCellID)
        
        return cv
    
    }()

}

//MARK: 实现表情视图的数据源方法  和代理方法
extension HMEmoticonKeyboardView : UICollectionViewDataSource,UICollectionViewDelegate{

    //返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    //每组有多少个items
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //根据每组表情的二维数组的个数 即页数
        return packages[section].sectionEmoticon.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonCellID, forIndexPath: indexPath) as! HMEmoticonPageCell
        
        //设置个颜色
//        cell.backgroundColor = randomColor()
        
        cell.emoticons = packages[indexPath.section].sectionEmoticon[indexPath.item]
        
        return cell
        
    }
    
//    //减速结束的时候 显示滚动到哪一页即cell的位置 此方法不是太准确
//    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
//        
//        //可视化路径数组
//        let indexPaths = EmoticonView.indexPathsForVisibleItems()
//        
//        //获取减速结束后显示的cell的路径 即数组的最后一个
//        let indexPath = indexPaths.last
//        
//        //设置toolbar的三个按钮的设置
//        toolbar.setSelectBtn(indexPath!.section)
//        
//        updatePagecontroll(indexPath!)
//    }
    
    //滚动的时候调用此方法 看每一页是否过了中心点来判断当前的页数
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //获取中心点
        var center = EmoticonView.center
        
        //获取翻动的X值
        center.x = center.x + EmoticonView.contentOffset.x
 
        //可视化路径数组
        let indexPaths = EmoticonView.indexPathsForVisibleItems()
        
        //获取减速结束后显示的cell的路径 即数组的最后一个
//        let indexPath = indexPaths.last
        
        //判断滚动的时候 上一页或者下一页只要过了这个中心点 就算是另一页
        for indexPath in indexPaths {
            
            let cell = EmoticonView.cellForItemAtIndexPath(indexPath)
            
            if cell!.frame.contains(center) {
                
                  //设置toolbar的三个按钮的设置
                toolbar.setSelectBtn(indexPath.section)
                
                updatePagecontroll(indexPath)
                
            }
            
        }
        
        
    }
    
    func updatePagecontroll(indexPath:NSIndexPath) {
    
        //设置滚动的时候 下面的分页指示器跟着变化
        pageControl.numberOfPages = packages[indexPath.section].sectionEmoticon.count
        pageControl.currentPage = indexPath.item

    
    }

}
